package com.zxshhy.service.impl;

import com.zxshhy.entity.Order;
import com.zxshhy.entity.OrderStatus;
import com.zxshhy.mapper.OrderTCCMapper;
import com.zxshhy.service.OrderTCCService;
import com.zxshhy.vo.OrderVo;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class OrderTCCServiceImpl implements OrderTCCService {
    @Resource
    private OrderTCCMapper orderTCCMapper;

    /**
     * try一阶段：订单创建
     * @param orderVo
     * @param orderId
     * @return
     */
    @Override
    public Order prepareSaveOrder(OrderVo orderVo, Long orderId) {
        // 保存订单
        Order order = new Order();
        order.setId(orderId);
        order.setUserId(orderVo.getUserId());
        order.setCommodityCode(orderVo.getCommodityCode());
        order.setCount(orderVo.getCount());
        order.setMoney(orderVo.getMoney());
        order.setStatus(OrderStatus.INIT.getValue());
        Integer saveOrderRecord = orderTCCMapper.insert(order);
        log.info("创建订单{}", saveOrderRecord > 0 ? "成功" : "失败");
        if(saveOrderRecord == 0) throw new RuntimeException("TCC-->try一阶段：订单创建异常");
        return order;
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {
        // 获取订单id
        long orderId = Long.parseLong(actionContext.getActionContext("orderId").toString());
        //更新订单状态为支付成功
        Integer updateOrderRecord = orderTCCMapper.updateOrderStatus(orderId,OrderStatus.SUCCESS.getValue());
        log.info("更新订单[id:{}]状态：{}", orderId, updateOrderRecord > 0 ? "成功" : "失败");
        return updateOrderRecord>0;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        //获取订单id
        long orderId = Long.parseLong(actionContext.getActionContext("orderId").toString());
        //更新订单状态为支付失败
        Integer updateOrderRecord = orderTCCMapper.updateOrderStatus(orderId,OrderStatus.FAIL.getValue());
        log.info("更新订单[id:{}]状态：{}", orderId, updateOrderRecord > 0 ? "成功" : "失败");
        return updateOrderRecord > 0;
    }
}
